package com.hzjq.encrypt.ui

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import com.alibaba.fastjson.JSONObject
import com.hzjq.encrypt.AbsActivity
import com.hzjq.encrypt.R
import com.hzjq.encrypt.bean.AuthBean
import com.hzjq.encrypt.bean.AuthDataBean
import com.hzjq.encrypt.bean.EnBean
import com.hzjq.encrypt.encrypt.EncryptUtils
import com.hzjq.encrypt.pop.SqrqPop
import com.hzjq.encrypt.util.Devider
import com.hzjq.encrypt.util.EToast
import com.hzjq.encrypt.util.FileStreamX
import com.hzjq.encrypt.util.KeyBoradX
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.FileCallback
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_gzm_layout.*
import kotlinx.android.synthetic.main.layout_en_info.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.io.FileInputStream

class GzmActivity : AbsActivity() {

    companion object {
        fun start(context: Context){
            val intent = Intent(context, GzmActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val param = HashMap<String,String>()

    private var encrypt: EnBean? = null


    override fun onCreated() {
        OkGo.getInstance().init(application)
        offPostResultLayout.visibility = View.GONE
        hideMore()
        setOnEncryptItemClick()
        EventBus.getDefault().register(this)
        gzmPostBtn.setOnClickListener {
            onSubmit()
        }
        gzmVEt.setText(Devider.getVersionName(this))
        gzmMacText.setText(Devider.getWlanMacAddress())
    }

    private fun onSubmit(){
        if(TextUtils.isEmpty(gzmServerHttpEt.text)){
            EToast.toast("请输入信息服务器地址")
            return
        }

        if(TextUtils.isEmpty(gzmQbqBhEt.text)){
            EToast.toast("请输入提取码")
            return
        }

        if(TextUtils.isEmpty(gzmVEt.text)){
            EToast.toast("请输入版本号")
            return
        }

        if(TextUtils.isEmpty(gzmDownServerHttpEt.text)){
            EToast.toast("请输入下载授权地址")
            return
        }

        if(TextUtils.isEmpty(gzmMacText.text)){
            EToast.toast("请输入mac地址")
            return
        }

        hideKeyBord()

        param["action"] = "getLicenseFile"
        param["code"] = if(TextUtils.isEmpty(gzmQbqBhEt.text)) "" else gzmQbqBhEt.text.toString()
        param["mac"] = if(TextUtils.isEmpty(gzmMacText.text)) "" else gzmMacText.text.toString()
        param["versionid"] = if(TextUtils.isEmpty(gzmVEt.text)) "" else gzmVEt.text.toString()


        val show = XPopup.Builder(this)
            .asLoading("正在请求中...")
            .show()

        OkGo.get<String>(gzmServerHttpEt.text.toString())
            .params(param)
            .execute(object : StringCallback(){
                override fun onSuccess(response: Response<String>?) {
                    if(response != null){
                        if(response.isSuccessful && !TextUtils.isEmpty(response.body())){
                            val ad = JSONObject.parseObject(response.body(), AuthDataBean::class.java)
                            if(ad.List.isNullOrEmpty()){
                                gzmPostResultText.visibility = View.VISIBLE
                                offPostResultLayout.visibility = View.GONE
                                gzmPostResultText.text = "没有找到授权结果。"
                            } else {
                                loadEnData(ad.List[0],show)
                            }
                        }
                    }
                }

                override fun onFinish() {

                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                    show.dismiss()
                    gzmPostResultText.visibility = View.VISIBLE
                    offPostResultLayout.visibility = View.GONE
                    gzmPostResultText.text = "请求错误\n${response?.exception}"
                }
            })
    }


    private fun loadEnData(auth: AuthBean,show: BasePopupView){
        OkGo.get<File>(gzmDownServerHttpEt.text.toString()+"/"+auth.filepath)
            .execute(object : FileCallback(FileStreamX.getOutDir(this),auth.filepath){
                override fun onSuccess(response: Response<File>?) {
                    if(response != null){
                        if(response.isSuccessful){
                            val read = FileStreamX.read(FileInputStream(response.body()))
                            val result = EncryptUtils.decodeNoURL(read, EncryptUtils.DE_KEY_BASE + gzmQbqBhEt.text)
                            val enBean = JSONObject.parseObject(result, EnBean::class.java)
                            enBean.filePath = response.body().absolutePath
                            enBean.code = gzmQbqBhEt.text.toString()
                            EventBus.getDefault().post(enBean)
                        }
                    }
                }

                override fun onFinish() {
                    super.onFinish()
                    show.dismiss()
                }
            })


    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun showEncrypt(encrypt: EnBean) {
        this.encrypt = encrypt
        runOnUiThread {
            gzmPostResultText.visibility = View.GONE
            offPostResultLayout.visibility = View.VISIBLE
            encrypt.lgs?.let { encryptLg.text = it.lg.size.toString() + "发" }
            encrypt.jbqys?.let { encryptJb.text = it.jbqy.size.toString() + "个区域" }
            encrypt.zbqys?.let { encryptZb.text = it.zbqy.size.toString() + "个区域" }
            encrypt.sbbhs?.let { encryptQbq.text = it.size.toString() + "台起爆器" }
            encryptSqrq.text = encrypt.sqrq
        }
    }

    private fun setOnEncryptItemClick() {
        encryptLg.setOnClickListener {
            hideKeyBord()
            LgEditorActivity.start(this, encrypt)
        }
        encryptJb.setOnClickListener {
            hideKeyBord()
            JbqyActivity.start(this, encrypt)
        }
        encryptZb.setOnClickListener {
            hideKeyBord()
            ZbqyActivity.start(this, encrypt)
        }
        encryptQbq.setOnClickListener {
            hideKeyBord()
            QbqActivity.start(this, encrypt)
        }
        encryptSqrq.setOnClickListener {
            hideKeyBord()
            SqrqPop.show(this, object : SqrqPop.OnSqrqEditorCallback {
                override fun onSqrqEditor(time: String) {
                    if (encrypt == null) {
                        encrypt = EnBean()
                    }
                    encrypt?.sqrq = time
                    if (encrypt != null) {
                        showEncrypt(encrypt!!)
                    }
                }
            }, if (encrypt == null) "" else encrypt!!.sqrq)
        }
    }


    private fun hideKeyBord() {
        KeyBoradX.hideKeyBoard(gzmQbqBhEt)
        KeyBoradX.hideKeyBoard(gzmVEt)
        KeyBoradX.hideKeyBoard(gzmServerHttpEt)
        KeyBoradX.hideKeyBoard(gzmDownServerHttpEt)
        KeyBoradX.hideKeyBoard(gzmMacText)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        hideKeyBord()
    }

    override fun getContentViewId(): Int {
        return R.layout.activity_gzm_layout
    }

    override fun getShowTitle(): String {
        return "工作码下载授权信息"
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}